<template>
  <div class="rechange-confing">
    <div
      v-for="(item, index) in ruleForm.data"
      :key="`confing${index}`"
      class="confing-item-wrap"
    >
      <GradCoupon
        :ref="(el) => setGradRef(el, item, index)"
        :activityId="prop.activityId"
        :title="ruleForm.arr[index]"
        :items="confingItems"
        :rules="confingRules"
        :couponsList="optionsS.coupons"
      ></GradCoupon>
      <div class="confing-btn-wrap">
        <!-- 增加按钮 -->
        <el-button
          v-if="index < ruleForm.size && index === ruleForm.data.length - 1"
          type="primary"
          @click="clickAdd(index)"
          >增加</el-button
        >
        <!-- 删除按钮 -->
        <el-button
          v-if="ruleForm.data.length > 1"
          class="btn-delete"
          type="primary"
          @click="clickDelete(index)"
          >删除</el-button
        >
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import GradCoupon from '../gradCoupon.vue';
import { FormRules } from 'element-plus';
import { IS_INT } from '@/utils/verify';
import { queryActivity } from '@/service/apis/market';

interface Props {
  activityId?: string | any;
}
const prop = withDefaults(defineProps<Props>(), {
  activityId: '',
});

let itemRefs: any = [];
const setGradRef = (el: any, item: any, index: number) => {
  if (el) {
    itemRefs[index] = el;
  }
};

const confingItems = reactive({
  label: '充值金额',
  unit: '元',
  prop: 'qualifiedAmount',
  placeholder: '请输入充值金额',
});
const confingRules = reactive<FormRules>({
  qualifiedAmount: [
    { required: true, message: '请输入充值金额', trigger: 'blur' },
    {
      pattern: IS_INT,
      message: '请输入正确的充值金额，正整数',
      trigger: 'blur',
    },
  ],
});

const optionsS = reactive({
  coupons: [] as any,
});

// 获取下拉优惠券
const getCouponList = () => {
  queryActivity({}).then((res: any) => {
    optionsS.coupons = res.map((item: any) => {
      return { label: item.name, value: item.id, count: item.restCount };
    });
  });
};

getCouponList();

const ruleForm = reactive({
  size: 9,
  arr: [
    '一级配置',
    '二级配置',
    '三级配置',
    '四级配置',
    '五级配置',
    '六级配置',
    '七级配置',
    '八级配置',
    '九级配置',
    '十级配置',
  ],
  data: [] as any,
});
if (!prop.activityId) {
  ruleForm.data.push({
    qualifiedAmount: '',
  });
}

// 校验
const validateAll = async () => {
  const objs = {} as any;
  let flag = true;
  const len = ruleForm.data.length;
  for (let i = 0; i < len; i++) {
    const obj = await itemRefs[i].getData(String(i));
    if (obj) {
      objs[i] = obj;
    } else {
      flag = false;
    }
  }
  return { items: objs, flag: flag };
};

// 增加
const clickAdd = async (index: number) => {
  const obj: any = await validateAll();
  if (obj.flag) {
    ruleForm.data.splice(index + 1, 0, {
      qualifiedAmount: '',
    });
  }
};

// 删除
const clickDelete = (index: number) => {
  ruleForm.data.splice(index, 1);
};

const getData = async () => {
  const obj: any = await validateAll();
  if (!obj.flag) {
    return false;
  }
  let num = 0;
  let flag = true;
  console.log('222-----', num, obj.items);
  for (const key in obj.items) {
    const amount = Number(obj.items[key][0].qualifiedAmount);
    if (amount > num) {
      num = amount;
    } else {
      console.log('111-----', key, num, amount);
      flag = false;
    }
  }
  if (!flag) {
    ElMessage({
      showClose: true,
      message: '充值梯度配置需要从小到大',
      type: 'warning',
    });
    return false;
  }

  return obj.items;
};

const setData = (data: any) => {
  let index = 0;
  console.log('ddd--222--', data);
  ruleForm.data = [];
  for (const key in data) {
    data[key].forEach((item: any) => {
      item.qualifiedAmount = String(Number(item.qualifiedAmount));
    });
    ruleForm.data.push({
      qualifiedAmount: data[key][0].qualifiedAmount,
    });
    index++;
  }
  nextTick(() => {
    const len = ruleForm.data.length;
    ruleForm.data.forEach((item: any, index: number) => {
      itemRefs[index]?.setData(data[index]);
    });
  });
};

defineExpose({
  getData,
  setData,
});
</script>

<style lang="scss">
.rechange-confing .confing-item-wrap {
  position: relative;
  width: 666px;
  .confing-btn-wrap {
    position: absolute;
    top: 8px;
    right: 8px;

    .btn-delete {
      --el-button-bg-color: #fa3939;
      --el-button-hover-bg-color: #f45a5a;
      --el-button-border-color: #fa3939;
      --el-button-active-bg-color: #da3636;
      --el-button-hover-border-color: #f45a5a;
      --el-button-active-border-color: #f45a5a;

      &:hover {
        --el-button-hover-bg-color: #f45a5a;
      }
    }
  }
}
</style>